#include "array.h"
#include <stdexcept>

#define non_val 999999


Array::Array(size_t size)
{
	if(size > 0)
	{
		total_size = size;
		my_size = size;
		data = new int[total_size];
		for(int i = 0; i < (int)total_size; i++)
		{
			data[i] = non_val;
		}
	}
	else
	{
		total_size = 0;
		my_size = 0;
		data = NULL;
	}
}

Array::Array(const Array& array)
{
	if(array.total_size > 0)
	{
		total_size = array.total_size;
		my_size = array.my_size;
		data = new int[total_size];
		for(int i = 0; i < (int)total_size; i++)
		{
			data[i] = array.data[i];
		}				
	}
	else
	{
		my_size = 0;
		data = NULL;
	}
}

int Array::get(int index) const
{
	if(index < 0)
	{
		index = 0;
	}
	if(index >= (int)my_size)
	{
		index = my_size-1;
	}

	if(data[index] == non_val)
	{
		throw runtime_error("Reading not existent data");
	}
				
	return data[index];		
}

void Array::set(int index, int value)
{
	if(index < 0)
	{
		index = 0;
	}
	if(index >= (int)total_size)
	{
		index = total_size-1;
	}
			
	data[index] = value;	
}

Array & Array::operator =(const Array &array)
{
	Array tmp(total_size);
	std::swap(data, tmp.data);
	return *this;
}

size_t Array::get_size() const
{
	return total_size;
}

void Array::push_back(int value)
{
	if(total_size > my_size)
	{
		data[my_size] = value;
		my_size++;
	}
	else
	{
		Array tmp(2*total_size);

		for(int i = 0; i < (int)my_size; i++)
		{
			tmp.data[i] = data[i];
		}
		for(int i = (int)my_size; i < 2*(int)total_size; i++)
		{
			tmp.data[i] = non_val;
		}
		tmp.data[my_size] = value;
		tmp.total_size = 2*my_size;
		tmp.my_size = my_size+1;

		std::swap(data, tmp.data);
	}
	
}

Array::~Array()
{
	if(data != NULL)
	{
		delete[] data;
	}
}


